/**
 * csv,xlsx数据导入组件
 */
import React from "react";
import { Upload, Button, Icon } from "antd";
import XLSX from "xlsx";
import _ from "lodash";
import { setDefaultAttrs } from "@/hooks/tools";

export default function (props) {
  setDefaultAttrs(props, {
    accept: ".csv,.xlsx",
    showUploadList: false,
    fieldNames: null,
    beforeUpload: (file, fileList) => {
      if (props.fieldNames) {
        transformToList(file);
      } else {
        props.onChange(file, fileList);
      }
      return false;
    }
  });
  function transformToList(file) {
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = e => {
      var workbook = XLSX.read(e.target.result, { type: "binary" });
      var sheet = workbook.Sheets.Sheet1;
      var list = [];
      var keyObj = props.fieldNames;
      _.forEach(sheet, (value, key) => {
        if (/^[A-Z]/.test(key)) {
          var keyStr = key[0];
          var index = key.slice(1) - 2;
          if (index > -1) {
            var k = keyObj[keyStr];
            if (list[index]) {
              list[index][k] = value.v;
            } else {
              list[index] = {};
              var k = keyObj[keyStr];
              list[index][k] = value.v;
            }
          }
        }
      });
      props.onChange(list);
    };
  }
  return (
    <Upload {...props}>
      <>
        {props.children ? (
          props.children
        ) : (
          <Button type="primary" size="small">
            {!props.loading ? (
              <Icon
                style={{ fontSize: 17 }}
                type="folder-add"
                theme="filled"
                twoToneColor="#fff"
              />
            ) : (
              <Icon
                style={{ fontSize: 17 }}
                type="loading"
                twoToneColor="#fff"
              />
            )}
          </Button>
        )}
      </>
    </Upload>
  );
}
